package com.atguigu.guli.service.trade.controller.api;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.trade.feign.EduFeignClient;
import com.atguigu.guli.service.trade.service.OrderService;
import com.atguigu.guli.service.trade.service.PayLogService;
import com.atguigu.guli.service.trade.util.WeixinPayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/api/trade/WX/pay/")
public class ApiWXPayController {
    @Autowired
    WeixinPayProperties weixinPayProperties;

    @Autowired
    OrderService orderService;

    @Autowired
    EduFeignClient eduFeignClient;
    @Autowired
    PayLogService payLogService;
    //获取支付的二维码
    @GetMapping("/auth/createNative/{orderId}")
    public R createNative(HttpServletRequest request, @PathVariable String orderId) {
      return   orderService.createNative(request,orderId);
//        //封装请求参数
//        try {
//            String code_url;
//            Order order = orderService.getById(orderId);
//            HashMap<String, String> map = new HashMap<>();
//            map.put("appid", weixinPayProperties.getAppId());
//            map.put("mch_id", weixinPayProperties.getPartner());
//            //随机字符串
//            String nonceStr = WXPayUtil.generateNonceStr();
//            map.put("nonce_str", nonceStr);
//            //签名:根据最终的map集合及特定的key由WXPayUtil中的方法生成
////        map.put("sign",)
//            //商品描述
//            map.put("body", order.getCourseTitle());
//            map.put("out_trade_no", order.getOrderNo());
//            map.put("total_fee", order.getTotalFee().toString());
//            map.put("spbill_create_ip", request.getRemoteHost());
//            map.put("notify_url", weixinPayProperties.getNotifyUrl());
//            map.put("trade_type", "NATIVE");
//            //将map转为xml格式的string字符串
//            String signature = WXPayUtil.generateSignature(map, weixinPayProperties.getPartnerKey());
//            map.put("sign", signature);
//            String xml = WXPayUtil.mapToXml(map);
//            HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");
//            client.setXmlParam(xml);
//            client.post();
//            String content = client.getContent();
//            System.out.println("content = " + content);
//            //向微信发送完请求后，进行验证签名等属性是否有误
//            Map resultMap = WXPayUtil.xmlToMap(content);
//            String s = resultMap.toString();
//            System.out.println("s = " + s);
//            Object return_code = resultMap.get("return_code");
//            Object return_msg = resultMap.get("return_msg");
//            String sign = resultMap.get("sign").toString();
//            //验证签名是否一致
//            if (!WXPayUtil.isSignatureValid(content, weixinPayProperties.getPartnerKey())) {
//                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
//            }
//            if (return_code == null || return_msg == null || !"SUCCESS".equals(return_code)) {
//                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
//            } else if ("SUCCESS".equals(return_code) && !"OK".equals(return_msg)) {
//                System.out.println(map.get("err_code"));
//                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
//            } else {
//                code_url = resultMap.get("code_url").toString();
//            }
//            return R.ok().data("code_url", code_url)
//                    .data("out_trade_no", order.getOrderNo())
//                    .data("total_fee", order.getTotalFee())
//                    .data("orderId", order.getId())
//                    .data("courseId", order.getCourseId());
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
//        }
    }

    //微信支付后的回调接口
    @PostMapping("/callback")
    public String callback(HttpServletRequest request, HttpServletResponse response){
        return orderService.callback(request,response);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("return_code","FAIL");
//        try {
//            ServletInputStream inputStream = request.getInputStream();
//            String result = StreamUtils.inputStream2String(inputStream, "UTF-8");
//            //判断签名是否正确
//            if (!WXPayUtil.isSignatureValid(result,weixinPayProperties.getPartnerKey())) {
//                map.put("return_msg","签名失败");
//                return WXPayUtil.mapToXml(map);
//            }
//            Map<String, String> xmlMap = WXPayUtil.xmlToMap(result);
//            if (xmlMap==null||xmlMap.get("return_code")==null
//                    ||!"SUCCESS".equals(xmlMap.get("return_code"))
//                    ||xmlMap.get("result_code")==null
//                    ||!"SUCCESS".equals(xmlMap.get("result_code"))
//            ){
//                map.put("return_msg","通知结果校验失败");
//                return WXPayUtil.mapToXml(map);
//            }
//            //判断支付金额是否正确
//            //查询订单信息
//            String tradeNo = xmlMap.get("out_trade_no");
//            LambdaQueryWrapper<Order> queryWrapper  = new LambdaQueryWrapper<>();
//            queryWrapper.eq(Order::getOrderNo,tradeNo);
//            Order order = orderService.getOne(queryWrapper);
//            //如果订单不为空，且支付状态为已支付，则给微信端支付成功的应答（这里的支付状态谁来更改呢？）
//            if (order!=null&& order.getStatus()==1){
//                map.put("return_msg","OK");
//                map.put("return_code","SUCCESS");
//                return WXPayUtil.mapToXml(map);
//            }else if (order==null||!xmlMap.get("cash_fee").equals(order.getTotalFee().toString())){
//                    map.put("return_msg","支付金额错误");
//                    return WXPayUtil.mapToXml(map);
//            }
//            //支付成功更新订单的支付状态
//            order.setStatus(1);
//            LambdaUpdateWrapper<Order> updatawarpper = new LambdaUpdateWrapper<>();
//            updatawarpper.set(Order::getStatus,1);
//            updatawarpper.set(Order::getPayType,1);
//            updatawarpper.eq(Order::getId,order.getId());
//             orderService.update(updatawarpper);
//
//             //保存支付日志
//            PayLog payLog = new PayLog();
//            payLog.setOrderNo(tradeNo);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//            String time_end = xmlMap.get("time_end");
//            Date date = dateFormat.parse(time_end);
//            payLog.setPayTime(date);
//            payLog.setTotalFee(order.getTotalFee());
//            payLog.setTransactionId(xmlMap.get("transaction_id"));
//            payLog.setTradeState("已完成");
//            payLog.setPayType(1);
//            payLog.setAttr(result);
//            payLogService.save(payLog);
//            //更新课程销量，远程调用edu接口，修改课程的销量
//            eduFeignClient.updateCourseSale(order.getCourseId());
//            //给wx服务器应答
//            map.put("return_msg","OK");
//            map.put("return_code","SUCCESS");
//            return WXPayUtil.mapToXml(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            map.put("return_msg" , "通知解析异常");
//            try {
//                return WXPayUtil.mapToXml(map);
//            } catch (Exception ex) {
//                ex.printStackTrace();
//                throw new GuliException(ResultCodeEnum.UNKNOWN_REASON);
//            }
//        }
    }
}